{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "be50b177",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-07T08:16:30.014279Z",
     "start_time": "2024-07-07T08:16:29.963446Z"
    }
   },
   "outputs": [],
   "source": [
    "import pymysql\n",
    "from datetime import datetime, timedelta\n",
    "def insert(clmc,zs):\n",
    "    conn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"196617\",\n",
    "                           charset=\"utf8\", db=\"whdserp_pro\")\n",
    "    cur = conn.cursor()\n",
    "    current_time = datetime.now()\n",
    "    print(current_time)\n",
    "    sql2 = \"insert into price(材料名称,指数,时间) values (%s,%s,%s)\"\n",
    "    try:\n",
    "        cur.execute(sql2,(clmc,zs,current_time))\n",
    "        conn.commit()\n",
    "        print(\"插入单条数据成功\")\n",
    "    except Exception as e:\n",
    "        print(e)\n",
    "        print(\"插入单条数据失败\")\n",
    "    finally:\n",
    "        cur.close()\n",
    "        conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee261444",
   "metadata": {
    "ExecuteTime": {
     "start_time": "2024-07-07T08:16:32.501Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-07-07 16:16:32.851787\n",
      "插入单条数据成功\n",
      "2024-07-07 16:16:32.876704\n",
      "插入单条数据成功\n",
      "[('水泥指数', '116.78'), ('矿粉指数', '50.69')]\n",
      "数据已保存至 stock_data2.csv\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import pandas as pd\n",
    "import time\n",
    "\n",
    "def 抓取并保存数据():\n",
    "    url = 'https://www.ccement.com/'\n",
    "    response = requests.get(url)\n",
    "    soup = BeautifulSoup(response.text, 'html.parser')\n",
    "    \n",
    "    stock_ul = soup.find('ul', class_='stock_ul')\n",
    "    \n",
    "    cement_index_elements = stock_ul.find_all('li', class_='stock_item down')\n",
    "    \n",
    "    # 只抓取第一个和第四个元素\n",
    "    data = []\n",
    "    if len(cement_index_elements) >= 4:\n",
    "        element1 = stock_ul.find('li', class_='stock_item up')\n",
    "        element2 = cement_index_elements[1]\n",
    "        \n",
    "        name1 = element1.find('span').text.strip()\n",
    "        stock_index1 = element1.find('p', class_='stock_index').text.strip()\n",
    "        \n",
    "        name2 = element2.find('span').text.strip()\n",
    "        stock_index2 = element2.find('p', class_='stock_index').text.strip()\n",
    "        \n",
    "        data.append((name1, stock_index1))\n",
    "        data.append((name2, stock_index2))\n",
    "        insert(name1, stock_index1)\n",
    "        insert(name2, stock_index2)\n",
    "    \n",
    "    # 转换数据为DataFrame\n",
    "    df = pd.DataFrame(data, columns=['名称', '指数'])\n",
    "    print(data)\n",
    "    \n",
    "    # 保存至CSV\n",
    "    file_name = 'stock_data2.csv'\n",
    "    df.to_csv(file_name, index=False)\n",
    "    print(f\"数据已保存至 {file_name}\")\n",
    "\n",
    "# 每隔一分钟运行脚本\n",
    "while True:\n",
    "    抓取并保存数据()\n",
    "    time.sleep(5)  # 暂停60秒"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95c8c362",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca3737d0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
